<?php
/**
 * Created by PhpStorm.
 * User: yuliang
 * Date: 2017/5/30
 * Time: 下午2:33
 */

namespace app\webapi\controller;


use app\common\controller\Api;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Db;
use think\Request;

class Qiniu extends Api
{

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }


    public function getQiniuToken(){
        // 参数校验
        $uid = input('post.uid');
        $token = input('post.token');
        $validate = $this->validate(['token'=>$token,'uid'=>$uid],['token'=>'require','uid'=>'require|number']);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        //验证token 以及用户 登录用户才能上传
        $checkToken = $this->checkAuthToken(input('post.token'));
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $user = Db::name('oauth_user')->where('uid',input('post.uid'))->where('status',1)->find();
        if(!$checkToken && !$user){
            return api_error('1000','用户校验失败！');
        }
        //根据用户ID 判断用户是否能上传图片(非必须)

        //获取qiniu授权操作

        $bucket = config('qiniu.bucket');
        $accessKey = config('qiniu.access_key');
        $secretKey = config('qiniu.secret_key');
        $auth = new Auth($accessKey, $secretKey);
//        $key = config('qiniu.site_url').'upload/avatar/'.date('Ymd').'/'.md5($uid);
        $key = 'upload/avatar/'.date('Ymd').'/'.md5($uid);
        $policy = array(
            'scope' => "$bucket:$key",
            'saveKey' => $key,
            'callbackUrl' => 'https://api.haibinjiaoyu.com/index.php?s=webapi/qiniu/qiniuCallback',
            'callbackBody' => '{"fname":"$(fname)", "fkey":"$(key)", "desc":"$(x:desc)", "uid":' . $uid . '}',
            'callbackBodyType' => 'application/json',
            'insertOnly' => 0,
            'mimeLimit' => 'image/*',
            'persistentOps' => 'imageView2/2/w/100/h/100',
        );
        $data['key'] = $key;
        $data['scope'] = "$bucket:$key";
//        $data['upToken'] = $upToken = $auth->uploadToken($bucket, null, 3600, $policy);
        $data['upToken'] = $upToken = $auth->uploadToken($bucket, $key, 3600, $policy);
        header('Access-Control-Allow-Origin:*');
//        echo $upToken;
        return api_return('获取上传token成功！',$data);
    }

    public function qiniuCallback(){
//        header('Content-Type: application/json');
//        echo json_encode(['code': 200]);die;
        $_body = file_get_contents('php://input');
        $body = json_decode($_body, true);

        $data['uid'] = $uid = $body['uid'];
        $data['fname'] =$fname = $body['fname'];
        $data['fkey'] =$fkey = $body['fkey'];
        $data['description'] =$desc = $body['desc'];
        $data['create_time'] = $data['update_time'] =$ctime = date('Y-m-d H:i:s');

        //校验是否合法请求 可以在callbackBody里面加上token信息，然后进行自校验
        //自有业务逻辑处理 把数据入库，包含 用户uid，fkey
        $ok = Db::name('files_info')->insert($data);
//        $ok = Db::execute('INSERT INTO jy_files_info (uid, fname, fkey, createTime, description) VALUES (:uid, :fname, :fkey, :ctime, :desc);',['uid' => $uid, 'fname' => $fname, 'fkey' => $fkey, 'ctime' => $ctime, 'desc' => $desc]);
        header('Content-Type: application/json');
        if ($ok)
        {
            $updateTime = date('Y-m-d H:i:s');
            // 修改用户头像
            $data['fkey'] = config('qiniu.site_url').$fkey;
            $result = db('oauth_user')->where('uid',$uid)->update(['avatar'=>$data['fkey'],'update_time'=>$updateTime]);
            $resp = array('ret' => 'success', 'data' => $data);
            echo json_encode($resp);
        }else{
            //            $resp = $ok->errorInfo();
            http_response_code(500);
//            echo json_encode($resp);
            return;
        }
    }

    public function getUpToken(){
        // 参数校验
        $uid = input('post.uid');
        $token = input('post.token');
        $id = input('post.id');


        $validate = $this->validate(['token'=>$token,'uid'=>$uid],['token'=>'require','uid'=>'require|number']);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        //验证token 以及用户 登录用户才能上传
        $checkToken = $this->checkAuthToken(input('post.token'));
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $user = Db::name('admin')->where('id',input('post.uid'))->where('status',1)->find();
        if(!$checkToken && !$user){
            return api_error('1000','用户校验失败！');
        }
        //根据用户ID 判断用户是否能上传图片(非必须)

        //获取qiniu授权操作

        $bucket = config('qiniu.bucket');
        $accessKey = config('qiniu.access_key');
        $secretKey = config('qiniu.secret_key');
        $auth = new Auth($accessKey, $secretKey);
//        $key = config('qiniu.site_url').'upload/avatar/'.date('Ymd').'/'.md5($uid);
        $key = 'uploads/file/'.date('Ymd').'/'.md5($id);
        $policy = array(
            'scope' => "$bucket:$key",
            'saveKey' => $key,
            'callbackUrl' => 'https://api.haibinjiaoyu.com/index.php?s=webapi/qiniu/uploadCallback',
            'callbackBody' => '{"fname":"$(fname)", "fkey":"$(key)", "desc":"$(x:desc)", "uid":' . $uid . ', "id":' . $id . '}',
            'callbackBodyType' => 'application/json',
            'insertOnly' => 0,
        );
        $data['key'] = $key;
        $data['scope'] = "$bucket:$key";
//        $data['upToken'] = $upToken = $auth->uploadToken($bucket, null, 3600, $policy);
        $data['upToken'] = $upToken = $auth->uploadToken($bucket, $key, 3600, $policy);
        header('Access-Control-Allow-Origin:*');
//        echo $upToken;
        return api_return('获取上传token成功！',$data);
    }

    public function uploadCallback(){
        $_body = file_get_contents('php://input');
        $body = json_decode($_body, true);

        $id = $body['id'];
        $data['uid'] = $uid = $body['uid'];
        $data['fname'] =$fname = $body['fname'];
        $data['fkey'] =$fkey = $body['fkey'];
        $data['description'] =$desc = $body['desc'];
        $data['create_time'] = $data['update_time'] =$ctime = date('Y-m-d H:i:s');

        //校验是否合法请求 可以在callbackBody里面加上token信息，然后进行自校验
        //自有业务逻辑处理 把数据入库，包含 用户uid，fkey
        header('Content-Type: application/json');
        $updateTime = date('Y-m-d H:i:s');
        // 修改用户头像
        $data['fkey'] = config('qiniu.site_url').$fkey;
        $result = db('course')->where('id',$id)->update(['file_url'=>$data['fkey'],'update_time'=>$updateTime]);
        $resp = array('ret' => 'success', 'data' => $data);
        echo json_encode($resp);

    }
}